package com.youlei.newgraduateproject.handler.exceptionhandler;

import com.youlei.newgraduateproject.entity.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * @author youlei
 * @version 1.0
 * @Date 2021-05-08-13:33
 * 全局的异常处理类
 */
//对在RestController那儿产生的异常进行捕获
@RestControllerAdvice
@Slf4j
public class GlobalExceptonHandler {


    // 实体校验异常捕获,前端传来的数据与后端的实体类(也可能是dto)不符
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handler(MethodArgumentNotValidException e) {

        BindingResult result = e.getBindingResult();
        ObjectError objectError = result.getAllErrors().stream().findFirst().get();

        log.error("实体校验异常：----------------{}", objectError.getDefaultMessage());
        return new CommonResult(400, "实体校验异常", objectError.getDefaultMessage());
    }



    //权限不足异常
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public CommonResult handler(AccessDeniedException e) {
        log.info("security权限不足：----------------{}", e.getMessage());
        return new CommonResult(403,"权限不足异常", e.getMessage());
    }

    //非法数据异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public CommonResult handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        return new CommonResult(400,"非法数据异常", e.getMessage());
    }

/*    //设置状态码
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    //设置捕获的异常类型
    @ExceptionHandler(value = RuntimeException.class)
    public CommonResult handler(RuntimeException e) {
        return new CommonResult(400, "运行时异常，"+e.getMessage(), e.getMessage());
    }*/
}
